package com.vesystem.vegua.config;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vesystem.vegua.exceptionConfig.ErrorCode;
import com.vesystem.vegua.exceptionConfig.ParameterInvalid;
import com.vesystem.vegua.utils.JwtToken;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @auther hcy
 * @create 2020-12-11 17:08
 * @Description
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println( request.getRequestURI() );
        String authHeader = request.getHeader(JwtToken.TOKEN_HEADER);
        if ( request.getMethod().toUpperCase().equals("OPTIONS") ){
            return true;
        }
        if ( authHeader ==null ){
            System.out.println("转发到登陆页");
            //response.sendRedirect("/static/remote/wuda/index.html");
            //return false;
            throw new ParameterInvalid(ErrorCode.VERIFY_JWT_FAILED);
        }else {
            // 登陆时如果token在缓存中查不到，这表示令牌无效、或者管理员将某个账户踢下线了，同样阻止登陆。
            if ( !authHeader.equals( ServerListener.TOKEN_CACHE.get(JwtToken.getUserLoginname(request)) ) ){
                throw new ParameterInvalid(ErrorCode.VERIFY_JWT_FAILED);
            }
            // token过期
            if ( JwtToken.isTokenExpired(request)  ){
                throw new ParameterInvalid(ErrorCode.TOKEN_EXPIRED);
            }
            //系统授权已过期
            if (ServerListener.SIGN.getExpiration()<System.currentTimeMillis()){
                // root 作为内置账户，不做任何限制
                if ( "root".equals( JwtToken.getUserLoginname(request) ) ){
                    return true;
                }else {
                    throw new ParameterInvalid(ErrorCode.SYSTEM_EXPIRES);
                }
            }
            return true;
        }
    }


}
